﻿#include "musicsendthread.h"

MusicSendThread::MusicSendThread(const QString &filePath, QObject *parent)
    : QThread(parent), filePath(filePath), isStop(false)
{
}

void MusicSendThread::run()
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file:" << filePath;
        return;
    }

    qint64 fileSize = file.size();
    qint64 bytesSent = 0;

    // 发送文件头信息
    QFileInfo fileInfo(filePath);
    QString header = QString("FILE:%1:%2\n").arg(fileInfo.fileName()).arg(fileSize);
    emit dataReady(header.toUtf8());  // 通过信号发送

    // 分块发送文件内容
    char buffer[4096];
    while (!isStop && !file.atEnd()) {
        qint64 bytesRead = file.read(buffer, sizeof(buffer));
        if (bytesRead > 0) {
            emit dataReady(QByteArray(buffer, bytesRead));  // 通过信号发送
            bytesSent += bytesRead;
        }
        QThread::msleep(1); // 稍微延迟，避免发送太快
    }

    file.close();

    // 发送结束标志
    if (!isStop) {
        emit dataReady("EOF\n");
    }

    qDebug() << "File sent:" << bytesSent << "/" << fileSize;
}
